package com.yxw.live_vod_backend_boot.util;

import com.volcengine.service.vod.IVodService;
import com.volcengine.service.vod.impl.VodServiceImpl;
import com.volcengine.service.vod.model.business.*;
import com.yxw.live_vod_backend_boot.vo.VodBandwidthDataVo;
import com.yxw.live_vod_backend_boot.vo.VodStorageDataVo;
import com.yxw.live_vod_backend_boot.vo.VodTrafficDataVo;
import com.yxw.live_vod_backend_boot.vo.VodTranscodeDataVo;
import com.yxw.yxnet_cd_center.common.exception.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 火山引擎操作工具类
 * liuxin
 * 2023.12.17
 */
@Component
@Slf4j
public class VolcanoEngineUtil {

    //火山引擎账号密钥ID
    @Value("${volcano.access_key_id:AKLTZGYxOWU3MGQyNTM2NDMyNTgzODExNjRhZTU1NDlmODk}")
    private String accessKeyId;

    //火山引擎账号密钥key
    @Value("${volcano.secret_access_key:TVdZMlptSTBaV0ZoTmpjMk5EUmxNemxoWkRjM1lqSTVOVFJtWTJWaE1XUQ==}")
    private String secretAccessKey;

    @Value("${volcano.video.space:yingxi-video}")
    private String videoSpace;


    /**
     * 查询带宽用量
     * @param startTime
     * @param endTime
     * @return
     */
    public VodBandwidthDataVo describeVodDomainBandwidthData(Date startTime, Date endTime) {
        IVodService vodService = VodServiceImpl.getInstance();
        vodService.setAccessKey(accessKeyId);
        vodService.setSecretKey(secretAccessKey);
        //默认都是O
        VodBandwidthDataVo vo = new VodBandwidthDataVo(0D,0D);
        try {
            com.volcengine.service.vod.model.request.VodDescribeVodDomainBandwidthDataRequest.Builder reqBuilder = com.volcengine.service.vod.model.request.VodDescribeVodDomainBandwidthDataRequest.newBuilder();
            //时间处理 RFC3339
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
            //查询的起始时间
            reqBuilder.setStartTime(format.format(startTime));
            //查询的结束时间
            reqBuilder.setEndTime(format.format(endTime));
            //聚合的时间粒度 86400：1 天
            reqBuilder.setAggregation(86400);
//            //带宽类型。默认值为 CDN。取值如下：
//            reqBuilder.setBandwidthType("CDN");
            com.volcengine.service.vod.model.response.VodDescribeVodDomainBandwidthDataResponse resp = vodService.describeVodDomainBandwidthData(reqBuilder.build());
            if (resp.getResponseMetadata().hasError()) {
                throw new BaseException(resp.getResponseMetadata().getError() + "");
            }
            log.info("查询带宽用量返回结果==============================>"+resp.toString());
            //解析参数
            VodDescribeVodDomainBandwidthDataResult result = resp.getResult();
            if(null!=result){
                //带宽峰值
                vo.setPeakBandwidth(result.getPeakBandwidth());
                List<VodBandwidthData> bandwidthDataListList = result.getBandwidthDataListList();
                //带宽
                vo.setBandwidth(bandwidthDataListList.get(0).getBandwidth());
            }
        } catch (Exception e) {
           log.error("带宽查询失败=========================================>："+e.getMessage());
        }
        return vo;
    }

    /**
     * 查询流量用量
     * @param startTime
     * @param endTime
     * @return
     */
    public VodTrafficDataVo describeVodDomainTrafficData(Date startTime, Date endTime) {
        IVodService vodService = VodServiceImpl.getInstance();
        vodService.setAccessKey(accessKeyId);
        vodService.setSecretKey(secretAccessKey);
        VodTrafficDataVo vo = new VodTrafficDataVo(0D);
        try {
            com.volcengine.service.vod.model.request.VodDescribeVodDomainTrafficDataRequest.Builder reqBuilder = com.volcengine.service.vod.model.request.VodDescribeVodDomainTrafficDataRequest.newBuilder();
            //时间处理 RFC3339
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
            //查询的起始时间
            reqBuilder.setStartTime(format.format(startTime));
            //查询的结束时间
            reqBuilder.setEndTime(format.format(endTime));
            //聚合的时间粒度 86400：1 天
            reqBuilder.setAggregation(86400);
//            //流量类
//            reqBuilder.setTrafficType("CDN");
            com.volcengine.service.vod.model.response.VodDescribeVodDomainTrafficDataResponse resp = vodService.describeVodDomainTrafficData(reqBuilder.build());
            if (resp.getResponseMetadata().hasError()) {
                throw new BaseException(resp.getResponseMetadata().getError() + "");
            }
            log.info("查询流量用量返回结果==============================>"+resp.toString());
            //解析参数
            VodDescribeVodDomainTrafficDataResult result = resp.getResult();
            vo.setTotalTraffic(result.getTotalTraffic()); ;
        } catch (Exception e) {
            log.error("查询流量用量信息失败=========================================>："+e.getMessage());
        }
        return vo;
    }

    /**
     * 查询存储用量
     * @param startTime
     * @param endTime
     * @return
     */
    public VodStorageDataVo describeVodSpaceStorageData(Date startTime, Date endTime) {
        IVodService vodService = VodServiceImpl.getInstance();
        vodService.setAccessKey(accessKeyId);
        vodService.setSecretKey(secretAccessKey);
        VodStorageDataVo vo = new VodStorageDataVo(0D);
        try {
            com.volcengine.service.vod.model.request.VodDescribeVodSpaceStorageDataRequest.Builder reqBuilder = com.volcengine.service.vod.model.request.VodDescribeVodSpaceStorageDataRequest.newBuilder();
            //时间处理 RFC3339
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
            //查询的起始时间
            reqBuilder.setStartTime(format.format(startTime));
            //查询的结束时间
            reqBuilder.setEndTime(format.format(endTime));
            //聚合的时间粒度。单位为秒。默认值为 86400，即 24 小时
            reqBuilder.setAggregation(86400);
            com.volcengine.service.vod.model.response.VodDescribeVodSpaceStorageDataResponse resp = vodService.describeVodSpaceStorageData(reqBuilder.build());
            if (resp.getResponseMetadata().hasError()) {
                throw new BaseException(resp.getResponseMetadata().getError() + "");
            }
            log.info("查询存储用量返回结果==============================>"+resp.toString());
            List<VodStorageData> storageDataListList = resp.getResult().getStorageDataListList();
            Long storage=0L;
            for (VodStorageData data: storageDataListList) {
                storage=storage+data.getStorage();
            }
            double one = Double.valueOf(storage/8/1024/1024/1024);
            DecimalFormat decimalFormat = new DecimalFormat("#.00");
            String str = decimalFormat.format(one);
            vo.setStorage(Double.parseDouble(str));
        } catch (Exception e) {
            log.error("查询存储用量失败=========================================>："+e.getMessage());
        }
        return vo;
    }

    /**
     * 查询转码用量
     * @param startTime
     * @param endTime
     * @return
     */
    public VodTranscodeDataVo describeVodSpaceTranscodeData(Date startTime, Date endTime) {
        IVodService vodService = VodServiceImpl.getInstance();
        vodService.setAccessKey(accessKeyId);
        vodService.setSecretKey(secretAccessKey);
        VodTranscodeDataVo vo=new VodTranscodeDataVo(0D);
        try {
            com.volcengine.service.vod.model.request.DescribeVodSpaceTranscodeDataRequest.Builder reqBuilder = com.volcengine.service.vod.model.request.DescribeVodSpaceTranscodeDataRequest.newBuilder();
            //时间处理 RFC3339
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
            //查询的起始时间
            reqBuilder.setStartTime(format.format(startTime));
            //查询的结束时间
            reqBuilder.setEndTime(format.format(endTime));
            //聚合的时间粒度。单位为秒。默认值为 86400，即 24 小时
            reqBuilder.setAggregation(86400);
            com.volcengine.service.vod.model.response.DescribeVodSpaceTranscodeDataResponse resp = vodService.describeVodSpaceTranscodeData(reqBuilder.build());
            if (resp.getResponseMetadata().hasError()) {
                throw new BaseException(resp.getResponseMetadata().getError() + "");
            }
            log.info("查询转码用量返回结果==============================>"+resp.toString());
            Long value=0l;
            List<DescribeVodSpaceTranscodeItem> totalTranscodeDataListList = resp.getResult().getTotalTranscodeDataListList();
            for (DescribeVodSpaceTranscodeItem item:totalTranscodeDataListList) {
                value= value+item.getValue();
            }
            double one = Double.valueOf(value/1000/60/24);
            DecimalFormat decimalFormat = new DecimalFormat("#.00");
            String str = decimalFormat.format(one);
            vo.setTransDuration(Double.parseDouble(str));
        } catch (Exception e) {
            log.error("查询转码用量失败=========================================>："+e.getMessage());
        }
        return vo;
    }
}
